// src/main/java/com/example/controller/CertificateController.java
package wsdc.app.main.v1;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.*;

@RestController
@RequestMapping("/api/cert")
public class CertificateController4 {

    @Autowired
    private CertificateService certificateService;

    /**
     * 1. 生成CA证书
     */
    @PostMapping("/ca")
    public ResponseEntity<Map<String, Object>> generateCACertificate(@RequestBody CertificateRequest request) {
        Map<String, Object> response = new HashMap<>();
        try {
            CertificateService.CertificateBundle caBundle = certificateService.createCa(request.getCommonName(), request.getOrganization(), request.getCountry(), request.getValidityYears());
            // 保存为文件
            certificateService.saveCertificateAsPEM(caBundle.getCertificate(), "ca-cert.pem");
            certificateService.savePrivateKeyAsPEM(caBundle.getPrivateKey(), "ca-key.pem");

            response.put("success", true);
            response.put("message", "CA证书生成成功");
            response.put("certificateFile", "ca-cert.pem");
            response.put("keyFile", "ca-key.pem");
        } catch (Exception e) {
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "CA证书生成失败: " + e.getMessage());
        }
        return ResponseEntity.ok(response);
    }


    /**
     * 3. 根据CA证书生成SSL证书（用于Tomcat）
     */
    @PostMapping("/ssl-tomcat-single")
    public ResponseEntity<Map<String, Object>> generateTomcatSSLCertificate0(@RequestBody(required = false) SSLCertificateRequest request) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 获取CA证书
            CertificateService.CertificateBundle caBundle = loadCABundle();

            // 生成用于Tomcat的SSL证书
            certificateService.createSslPkcs(caBundle, request.getCommonName(), request.getOrganization(), request.getCountry(), request.getSanDomains(), request.getValidityYears(), request.getPassword());

            response.put("success", true);
            response.put("message", "Tomcat SSL证书生成成功");
            response.put("keystoreFile", "certs/tomcat-ssl.p12");
            response.put("keystorePassword", request.getPassword());
            response.put("instructions", "在application.properties中添加以下配置：\n" + "server.port=8443\n" + "server.ssl.enabled=true\n" + "server.ssl.key-store=certs/tomcat-ssl.p12\n" + "server.ssl.key-store-password=" + request.getPassword() + "\n" + "server.ssl.key-store-type=PKCS12\n" + "server.ssl.key-alias=key");
        } catch (Exception e) {
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "Tomcat SSL证书生成失败: " + e.getMessage());
        }
        return ResponseEntity.ok(response);
    }

    /**
     * 生成支持泛域名的Tomcat SSL证书
     */
    @PostMapping("/tomcat-ssl-wildcard")
    public ResponseEntity<Map<String, Object>> generateWildcardSSLCertificate1(@RequestBody(required = false) WildcardSSLCertificateRequest request) {
        Map<String, Object> response = new HashMap<>();
        try {

            // 如果没有指定泛域名，但Common Name是通配符，则使用Common Name
            if (request.getWildcardDomain() == null || request.getWildcardDomain().isEmpty()) {
                if (request.getCommonName().startsWith("*.")) {
                    request.setWildcardDomain(request.getCommonName());
                } else {
                    request.setWildcardDomain("*." + request.getCommonName());
                }
            }

            // 获取CA证书
            CertificateService.CertificateBundle caBundle = loadCABundle();

            // 生成支持泛域名的SSL证书
            CertificateService.CertificateBundle sslBundle = certificateService.createSslWild(caBundle, request.getCommonName(), request.getOrganization(), request.getCountry(), request.getSanDomains(), request.getWildcardDomain(), request.getValidityYears(), request.getPassword());

            // 保存为PKCS12格式文件（Tomcat可以直接使用）
            certificateService.saveAsPKCS12WithChain(sslBundle.getCertificate(), sslBundle.getPrivateKey(), caBundle.getCertificate(), "wildcard-ssl.p12", request.getPassword());

            response.put("success", true);
            response.put("message", "泛域名SSL证书生成成功");
            response.put("keystoreFile", "certs/wildcard-ssl.p12");
            response.put("keystorePassword", request.getPassword());
            response.put("commonName", request.getCommonName());
            response.put("wildcardDomain", request.getWildcardDomain());
            response.put("sanDomains", request.getSanDomains() != null ? request.getSanDomains() : new String[0]);
            response.put("instructions", "在application.properties中添加以下配置：\n" + "server.port=8443\n" + "server.ssl.enabled=true\n" + "server.ssl.key-store=certs/wildcard-ssl.p12\n" + "server.ssl.key-store-password=" + request.getPassword() + "\n" + "server.ssl.key-store-type=PKCS12\n" + "server.ssl.key-alias=key");
            response.put("usage", "此证书支持以下域名模式：\n" + "1. " + request.getCommonName() + "\n" + "2. " + request.getWildcardDomain() + " (泛域名)\n" + (request.getSanDomains() != null ? "3. SAN域名: " + String.join(", ", request.getSanDomains()) : ""));
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "泛域名SSL证书生成失败: " + e.getMessage());
            e.printStackTrace();
        }
        return ResponseEntity.ok(response);
    }

    // 加载ca证书
    private CertificateService.CertificateBundle loadCABundle() throws Exception {
        File certFile = new File("d:/cert/certs/ca-cert.pem");
        File keyFile = new File("d:/cert/certs/ca-key.pem");

        // 如果文件存在，则从文件加载CA证书
        if (certFile.exists() && keyFile.exists()) {
            return certificateService.loadCACertificateFromDisk("d:/cert/certs/ca-cert.pem", "d:/cert/certs/ca-key.pem");
        }
        return null;
    }
}
